package com.mall.util;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall.pojo.MmallUser;

/**
 * 淘淘商城自定义响应结构
 */
public class JsonUtils {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串。
     * <p>Title: pojoToJson</p>
     * <p>Description: </p>
     * @param data
     * @return
     */
    public static String objectToJson(Object data) {
    	try {
			String string = MAPPER.writeValueAsString(data);
			return string;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    /**
     * 将json结果集转化为对象
     * 
     * @param jsonData json数据
     * @param clazz 对象中的object类型
     * @return
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 将json数据转换成pojo对象list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
    	JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
    	try {
    		List<T> list = MAPPER.readValue(jsonData, javaType);
    		return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	return null;
    }
    
    public static void main(String[] args) {
		
    	//测试
    	
    	Logger log = LoggerFactory.getLogger(JsonUtils.class);
    	MmallUser user = new MmallUser();
    	user.setId(1);
    	user.setAnswer("aaa");
    	
    	MmallUser user2 = new MmallUser();
    	user2.setId(2);
    	user2.setAnswer("bbb");
    	
    	List<MmallUser> list = new ArrayList<>();
    	list.add(user);
    	list.add(user2);
    	
    	log.info("======对象转为json=======");
    	String json = JsonUtils.objectToJson(user);
    	log.info(json);
    	
    	
    	log.info("=====json转为对象========");
    	MmallUser users = JsonUtils.jsonToPojo(json, MmallUser.class);
    	log.info("对象信息: {}",users.toString());
    	
    	
    	log.info("=====list转为json========\n");
    	String res = JsonUtils.objectToJson(list);
    	log.info(res);
    	
    	log.info("=====list转为json========\n");
    	//List<List> li = JsonUtils.jsonToList(res,(Li.class);
    	//log.info("集合 : {}\n",li);
    	
	}
    
}
